package com.sctvcloud.qingchuan.ui.dialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.ruihang.generalibrary.ui.dialog.BaseBottomSheetFrag;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.beans.FUsers;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.activities.SpeakActivity;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.ui.utils.KeyBoardUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;

public class PoliticsReplyDiaFragment extends BaseBottomSheetFrag implements View.OnClickListener {
    private CustomFontEditText comment_ct;
    private CustomFontTextView send;
    private SendComment sendComment;
    private CustomFontTextView count;
    public static final int REQUEST_CODE_VOICE = 3;
    public static final int REQUEST_CODE_LOGIN = 5;

    private long interactionId;
    private long parentReplyId;

    //    @Override
//    protected BottomSheetDialog creatBottomSheetDialog(Bundle savedInstanceState) {
//        BottomSheetDialog dialog = new BottomSheetDialog(getActivity(), R.style.BottomDialog);
//        Window window = dialog.getWindow();
//        dialog.setCanceledOnTouchOutside(true);// 外部点击取消
////        WindowManager.LayoutParams params = window.getAttributes();
////        params.gravity = Gravity.BOTTOM;
////        params.width = WindowManager.LayoutParams.MATCH_PARENT;
////        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
////        window.setAttributes(params);
////        window.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
//        return dialog;
//    }
    private int types;

    public int getTypes() {
        return types;
    }

    public void setTypes(int types) {
        this.types = types;
    }


    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int length = getStrLength(s.toString());
            count.setText(getString(R.string.comment_litmit_, length));
            if (length > 500) {
                toast(R.string.only_500_word);
            }

        }
    };

    @Override
    public int getLayoutResId() {
        return R.layout.dia_politics_reply_fragment;
    }


    public SendComment getSendComment() {
        return sendComment;
    }

    public PoliticsReplyDiaFragment setSendComment(SendComment sendComment) {
        this.sendComment = sendComment;
        return this;
    }

    public void onLoginSuc() {
        send.callOnClick();
    }

    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(this.getClass().getName(), ex.toString());
        }
        return null;
    }


    @Override
    public void initView() {
        comment_ct = (CustomFontEditText) rootView.findViewById(R.id.dia_comment_fragment_write_comment);
        send = (CustomFontTextView) rootView.findViewById(R.id.dia_comment_fragment_write_send);
        count = (CustomFontTextView) rootView.findViewById(R.id.comment_fragment_count);
        send.setOnClickListener(this);
        comment_ct.addTextChangedListener(watcher);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onClick(View v) {
        if (v == send) {
            String str = comment_ct.getText().toString();
            if (TextUtils.isEmpty(str)) {
                toast(R.string.please_input_comment);
                return;
            }
            replyPolitics(str);

            KeyBoardUtils.closeKeyboard(getActivity());
//            dismiss();
        }
    }

    private int getStrLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }

    public interface SendComment {
        boolean onCommentSendPrepare(int mode);

        void onCommentSendSuccess(int mode);

        void onCommentSendFinish(int mode, boolean isNetSuc);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_VOICE) {
            if (data != null) {
                String voice = data.getStringExtra(SpeakActivity.SEARCH_KEY);
                if (!TextUtils.isEmpty(voice)) {
                    comment_ct.setText(voice);
                }
            }
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        comment_ct.removeTextChangedListener(watcher);
        comment_ct.setText("");
        super.onDismiss(dialog);

    }

    /**
     * 发送问政追问
     *
     * @param content 追问内容
     * @return
     */
    private void replyPolitics(String content) {
        if (interactionId > 0 && parentReplyId > 0) {
            long userId = 0;
            FUsers user = UserManager.getInstance().getUser();
            if (null != UserManager.getInstance().getUser()) {
                String id = user.getUserId();
                if (!TextUtils.isEmpty(id)) {
                    userId = Long.parseLong(id);
                }
                Map<String, Object> formMaildata = new HashMap<>();
                formMaildata.put("interactionId", interactionId);
                formMaildata.put("relaId", userId);
                formMaildata.put("type", 1);
                formMaildata.put("content", content);
                formMaildata.put("nickName", user.getNickName());
                formMaildata.put("avatar", user.getAvatar());
                formMaildata.put("parentId", parentReplyId);
                RequestBody body = DataUtils.toRequestBody(formMaildata);
                NetUtils.getNetAdapter().toSendPoliticsReply(getOwnerName(), Constances.TENANT_ID, body, new AbsNetCallBack<String>(String.class) {
                    @Override
                    public void onSucStr(String news) {
                        comment_ct.setText("");
                        sendComment.onCommentSendSuccess(1);
                        closeProgress();
                        dismissAllowingStateLoss();
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        toast(errorMsg);
                    }


                    @Override
                    public void onEnd() {
                        closeProgress();
                    }
                });
            }
        } else {
            toast("选择回复错误");
        }
    }

    /**
     * 传入问政回复相关参数
     *
     * @param interactionId
     * @param parentReplyId
     */
    public void setReplyInfo(long interactionId, long parentReplyId) {
        this.interactionId = interactionId;
        this.parentReplyId = parentReplyId;
    }
}
